/*
 * @Author: fraser.zhangfeng
 * @Date: 2024-03-29 13:28:22
 * @Last Modified by: fraser.zhangfeng
 * @Last Modified time: 2024-03-29 13:35:15
 */
import { CCObject, JsonAsset, SpriteFrame, Texture2D, assetManager, resources } from "cc";

export class XLoader extends CCObject {

    static config(): void {
        // 重试下载的最大次数，默认 3 次
        assetManager.downloader.maxRetryCount = 3;
        // 重试下载的间隔时间，默认 2000 ms
        assetManager.downloader.retryInterval = 2000;
    }

    // `config/config`
    /** 加载json文件 */
    static loadJson(path: string,
        onComplete: (content: JsonAsset) => void, cbThis: any): void {
        resources.load(path, JsonAsset,
            (err: Error | null, data: JsonAsset) => {
                err && console.log(err);
                onComplete && onComplete.call(cbThis, data);
            });
    }


    /**
     * 加载 Spriteframe 文件
     * image 是 ImageAsset，spriteFrame 是 image/spriteFrame，texture 是 image/texture
    */
    static loadSpriteframe(path: string,
        onComplete: (content: SpriteFrame) => void, cbThis: any): void {
        resources.load(path, SpriteFrame,
            (err: Error | null, data: SpriteFrame) => {
                err && console.log(err);
                onComplete && onComplete.call(cbThis, data);
            });
    }

    /**
     * 加载 spriteFrame，texture 文件
     * image 是 ImageAsset，spriteFrame 是 image/spriteFrame，texture 是 image/texture
    */
    static loadTexture(path: string,
        onComplete: (content: Texture2D) => void, cbThis: any): void {
        resources.load(path, Texture2D,
            (err: Error | null, data: Texture2D) => {
                err && console.log(err);
                onComplete && onComplete.call(cbThis, data);
            });
    }

    static loadBundle(bundleName: string, path: string,
        onComplete: (content: Texture2D) => void, cbThis: any): void {
        assetManager.loadBundle(bundleName, function(err, bundle) {
            bundle.load(path, (err, asset: Texture2D) => {
                err && console.log(err);
                onComplete && onComplete.call(cbThis, asset);
            });
        });
    }
}